<template>
  <div class="commonTableSty">
    <a-table
      :columns="columns"
      :rowKey="(record, index) => record.level"
      :dataSource="configs"
      :pagination="false"
    >
      <template
        slot="auditHierarchy"
        slot-scope="text, record"
      >
        <span>{{ $t(`levelAudit${record.level}`) }}</span>
      </template>
      <!-- 审核角色 -->
      <template
        slot="auditRoles"
        slot-scope="text, record,index"
      >
        <a-select
          v-model="record.roleId"
          showSearch
          :placeholder="$t('pleaseSelect') + $t('role').toLowerCase()"
          optionFilterProp="children"
          :filterOption="$commonFun.filterOption"
          :disabled="record.disabled"
          @change="changeRole($event,index)"
          style="width:100%"
        >
          <a-select-option
            v-for="(item,indexer) in roleList"
            :key="indexer"
            :value="item.id"
            :title="item.name"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </template>
      <!-- 审核用户 -->
      <template
        slot="auditUsers"
        slot-scope="text, record,index"
      >
        <a-select
          :allow-clear="true"
          :value="record.userList && record.userList.length ? record.userIds : []"
          showSearch
          :placeholder="$t('pleaseSelect') + $t('auditUsers').toLowerCase()"
          optionFilterProp="children"
          :filterOption="$commonFun.filterOption"
          style="width:100%"
          :mode="isUse ? 'default' : 'multiple'"
          @change="changeUser($event,index)"
        >
          <a-select-option
            v-for="(item,indexer) in record.userList"
            :key="indexer"
            :value="item.id"
            :title="item.account"
          >
            {{ item.account }}
          </a-select-option>
        </a-select>
      </template>
      <template
        slot="action"
        slot-scope="text, record,index"
      >
        <a
          :disabled="record.disabled || index < minLevel || index !== configs.length - 1 "
          @click="handleDelete(index)"
        >{{ $t('delete') }}</a>
      </template>
    </a-table>
    <a-button
      class="newBtnWithPlus"
      @click="addlist"
      :disabled="configs.length + 1 >maxLevel"
    >
      +
    </a-button>
  </div>
</template>
<script>
import { mapGetters, mapState } from 'vuex'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import { configTbColumns } from './config/list'
import _ from 'lodash'
const initItem = {
  id: null,
  level: 1,
  roleId: undefined,
  userIds: [],
  userList: [],
  disabled: false
}
export default {
  name: 'AuditProcessList',
  components: {
    TableEllipsis,
    HasNoPermissionTip
  },
  props: {
    // 审核表格数据
    processList: {
      type: Array,
      required: true,
      default () {
        return []
      }
    },
    roleIds: {
      type: Array,
      default () {
        return []
      }
    },
    // true是在使用,使用时选择用户是单选,false是在配置模板
    isUse: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters(['logindomainCode']),
    ...mapState({
      roleList: (state) => state.role.roleData
    })
  },

  data () {
    return {
      columns: configTbColumns,
      // 最高层级(配置的时候至少一级，使用审核流程时至少得有所配置的级煺)
      maxLevel: 5,
      minLevel: 1,
      configs: []
    }
  },
  watch: {
    roleIds: {
      handler () {
        this.getSelectedRolesUserList()
      },
      immediate: true
    },
    processList: {
      handler (val) {
        this.handlingDefaultConfigs(val)
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    this.initData()
  },
  methods: {
    initData () {
      //   获取角色下拉框数据
      this.$store.dispatch('getRoleData')
    },
    handlingDefaultConfigs (val) {
      if (val.length) {
        this.configs = _.cloneDeep(val)
      } else {
        this.configs = [{ ...initItem }]
      }
    },
    // 选择角色
    changeRole (value, index) {
      const vm = this
      //   初始化用户
      vm.$set(vm.configs[index], 'userIds', [])
      vm.$set(vm.configs[index], 'userList', [])
      //   获取用户列表
      vm.getUserList(value, index)
    },
    // 获取用户下拉框数据
    getUserList (roleId, index) {
      const vm = this
      vm.$api.getUserSelect({ roleId }).then(response => {
        vm.$set(vm.configs[index], 'userList', response.data)
      })
    },
    // 获取默认已选择的角色对应的用户列表
    getSelectedRolesUserList () {
      this.roleIds.forEach((role, index) => {
        this.getUserList(role, index)
      })
    },
    changeUser (data, index) {
      console.log(data, 'data')
      this.$set(this.configs[index], 'userIds', data)
    },
    // 新增某条table
    addlist () {
      const vm = this
      const objItem = { ...initItem }
      objItem.level = vm.configs.length + 1
      if (objItem.level === 1) {
        objItem.disabled = false
      }
      vm.configs.push(objItem)
      console.log('11313addlist', vm.configs)
    },
    // 删除单行
    handleDelete (index) {
      const vm = this
      this.submitDisabled = false
      this.$confirm({
        title: vm.$t('deleteAuditProcess'),
        content: vm.$t('deleteAuditProcessTip'),
        onOk () {
          vm.configs.splice(index, 1)
          vm.$emit('changeSubmitDisabled', false)
        },
        onCancel () { }
      })
    },
    // 重置配置
    resetConfigs () {
      this.handlingDefaultConfigs(this.processList)
      this.getSelectedRolesUserList()
    },
    getConfigsData () {
      const result = this.validate()
      return result
    },
    // 检测表单数据
    validate () {
      // 检测是否有未填写的角色或者人
      console.log(this.configs, 'result')
      const result = this.configs.some(item => {
        return !item.roleId || !item.userIds || item.userIds.length === 0
      })
      if (result) {
        this.$message.error(this.$t('auditHasNoLevelTip'))
        return []
      }
      const items = this.configs.map(item => {
        const obj = {
          ...item
        }
        delete obj.userList
        return obj
      })
      return items
    }
  }
}
</script>
